package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.enums.EmployeeTypeEnum;
import com.ruoyi.common.enums.OrderState;
import com.ruoyi.common.utils.AutoCreateNumberUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.DealOrderDto;
import com.ruoyi.system.domain.dto.EmployeeAndReleationDto;
import com.ruoyi.system.domain.dto.EmployeeDto;
import com.ruoyi.system.domain.dto.OrderDetailDto;
import com.ruoyi.system.domain.dto.OrderDto;
import com.ruoyi.system.domain.vo.DealOrderVo;
import com.ruoyi.system.domain.vo.OrderDetailVo;
import com.ruoyi.system.domain.vo.OrderListVo;
import com.ruoyi.system.domain.vo.UpdateDealOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.expression.spel.ast.Literal;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OrderMapper;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.IOrderService;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;

import static com.ruoyi.common.constant.Constants.EMPLOYEE_NO;
import static com.ruoyi.system.execute.DictCacheManager.DICT_CACHE;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-20
 */

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EmployeeServiceImpl employeeService;

    @Value("${dict.order.hg}")
    private String dictOrderHg;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        order.setCreateTime(DateUtils.getNowDate());
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(DateUtils.getNowDate());
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }

    private static final Map<String, Map<String, Integer>> EMPLOYEE_DICT = new HashMap<>();

    @PostConstruct
    private void load() {
        if (Objects.nonNull(dictOrderHg)) {
            Map<String, Integer> map = new HashMap<>();
            EMPLOYEE_DICT.put(EmployeeTypeEnum.hg.name(), map);
            Arrays.stream(dictOrderHg.split(",")).forEach(x -> map.put(x, 1));
        }
    }

    private static Map<Integer, String> ORDER_STATE_CACHE = new HashMap<>();

    static {
        OrderState[] values = OrderState.values();
        for (OrderState value : values) {
            ORDER_STATE_CACHE.put(value.getState().intValue(), value.getDesc());
        }
    }

    @Override
    public DealOrderDto consumerDealOrder(DealOrderVo dealOrderVo) {

        String orderType = dealOrderVo.getPlatform();

        Map<String, Map<String, String>> outSideOrderData = dealOrderVo.getOrderData();

        Map<String, String> orderData = outSideOrderData.get(orderType);

        String employeeNo = orderData.get(EMPLOYEE_NO);

        Assert.notNull(employeeNo, "员工编号不能为空");

        Assert.notNull(dealOrderVo.getConsumerNo(), "客户编号不能为空");

        Order order = new Order();
        long orderNo = Long.parseLong(AutoCreateNumberUtil.generateNo("", 3));
        order.setOrderNo(orderNo);
        Map<String, Integer> map = EMPLOYEE_DICT.get(dealOrderVo.getPlatform());

        Set<Map.Entry<String, String>> entries = orderData.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (Objects.nonNull(map.get(entry.getKey()))) {
                entry.setValue(DICT_CACHE.get(Long.parseLong(entry.getValue())));
            }
        }
        order.setOrderDesc(JSONUtil.toJsonStr(orderData));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setOrderState(OrderState.noPay.getState());
        order.setOrderType(orderType);
        order.setEmployeeNo(employeeNo);
        order.setConsumerNo(dealOrderVo.getConsumerNo());
        orderMapper.insertOrder(order);

        return DealOrderDto.builder().orderStateDesc(OrderState.noPay.getDesc())
                .orderState(OrderState.noPay.getState()).orderNo(orderNo).orderType(dealOrderVo.getPlatform()).build();
    }

    @Override
    public DealOrderDto updateDealOrder(UpdateDealOrderVo updateDealOrderVo) {
        Assert.notNull(updateDealOrderVo.getOrderNo(), "订单编号为空");
        Order order = orderMapper.selectOrderByOrderNo(updateDealOrderVo.getOrderNo());
        if (Objects.isNull(order)) {
            return DealOrderDto.builder().build();
        }
        if (Objects.nonNull(updateDealOrderVo.getOrderData())) {
            order.setOrderDesc(JSONUtil.toJsonStr(updateDealOrderVo.getOrderData()));
        }
        order.setUpdateTime(new Date());
        int updateCount = orderMapper.updateOrder(order);
        if (updateCount > 1) {
            return DealOrderDto.builder().orderNo(updateDealOrderVo.getOrderNo()).build();
        }
        return null;
    }

    @Override
    public OrderDetailDto queryOrderDetail(OrderDetailVo orderDetailVo) {
        Order order = orderMapper.selectOrderByOrderNo(orderDetailVo.getOrderNo());
        Assert.notNull(order, "为查询到当前订单");
        String orderDesc = order.getOrderDesc();
        OrderDto orderDto = OrderDto.builder().orderJson(JSONObject.parse(orderDesc)).build();
        orderDto.setOrderDesc(null);
        BeanUtil.copyProperties(order, orderDto);
        orderDto.setOrderStateDesc(ORDER_STATE_CACHE.get(order.getOrderState()));
        String employeeNo = order.getEmployeeNo();
        Assert.notNull(employeeNo, "当前订单没有绑定员工编号");
        EmployeeDto employee = employeeService.getAllEmployeeByNo(order.getEmployeeNo());
        Assert.notNull(employee, "未查询到当前订单绑定的员工信息");
        EmployeeAndReleationDto employeeAndReleationDto = employeeService.parseEmployee(orderDetailVo.getPlatform(), null, employee, false);
        return OrderDetailDto.builder().orderData(orderDto).employeeInfo(employeeAndReleationDto).build();
    }

    @Override
    public List<OrderDto> queryDetailListByConsumerNo(OrderListVo orderListVo) {
        Order order = new Order();
        order.setConsumerNo(order.getConsumerNo());
        order.setOrderType(order.getOrderType());
        order.setPlatform(orderListVo.getPlatform());
        PageHelper.startPage(orderListVo.getPageNum(), orderListVo.getPageSize()).setOrderBy("create_time");
        List<Order> orders = orderMapper.selectOrderList(order);
        List<OrderDto> orderDtoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(orders)) {
            return null;
        }
        for (Order od : orders) {
            OrderDto dto = OrderDto.builder().build();
            BeanUtil.copyProperties(od, dto);
            dto.setOrderJson(JSONObject.parseObject(od.getOrderDesc()));
            dto.setOrderStateDesc(ORDER_STATE_CACHE.get(od.getOrderState()));
            orderDtoList.add(dto);
        }
        return orderDtoList;
    }
}
